package cn.easyutil.easyproject.easySpringboot.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.example.easyJavaUtil.JsonUtil;
import com.example.easyJavaUtil.StringUtil;
import cn.easyutil.easyproject.easySpringboot.bean.UserBean;
import cn.easyutil.easyproject.easySpringboot.context.Context;
import cn.easyutil.easyproject.easySpringboot.context.Error;
import cn.easyutil.easyproject.easySpringboot.exception.CommonException;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 请求临时对象缓存池
 */
@Component
public class RequestPool {
	
	@Value("${enableAuth}")
	private Boolean enableAuth;
	
	private static Boolean auth;
	
    /**
     * request临时对象池
     */
    private static ThreadLocal<HttpServletRequest> pool = new ThreadLocal<HttpServletRequest>();

    /**
     * 移除缓存
     */
    public static void remove() {
        pool.remove();
    }

    /**
     * 添加缓存
     */
    public static void set(HttpServletRequest request) {
        pool.set(request);

    }

    /**
     * 获取缓存
     */
    public static HttpServletRequest get() {
        return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
    }

    /**
     * 获取缓存session
     */
    public static HttpSession getSession() {
        return get().getSession();
    }

    /**
     * 获取用户id
     *
     * @return 返回用户id
     */
    public static Long getUserId() {
        return getUser().getId();
    }
    
    /**
     * 是否开启参数和返回数据的加解密
     * @return
     */
    public static Boolean enableAuth(){
    	return auth;
    }

    /**
     * 获取缓存用户
     *
     * @return
     */
    public static UserBean getUser() {
        if (get() == null) {
            return (UserBean) ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest().getSession().getAttribute(Context.session_user);
        }
        UserBean user = (UserBean) getSession().getAttribute(Context.session_user);
        if (user == null) {
            throw new CommonException(Error.biz_user_not_login);
        }
        return user;
    }

    public static UserBean getUserNotException() {
        if (get() == null) {
            return (UserBean) ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest().getSession().getAttribute(Context.session_user);
        }

        return (UserBean) getSession().getAttribute(Context.session_user);
    }

    /**
     * 缓存到session信息
     *
     * @param flag 缓存key
     * @param obj  缓存数据
     */
    public static void setSessionAttribute(String flag, Object obj) {
        if (get() == null) {
            ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest().getSession().setAttribute(flag, obj);
        } else {
            getSession().setAttribute(flag, obj);
        }
    }

    /**
     * 获取缓存到session信息
     *
     * @param flag 缓存key
     */
    public static Object getSessionAttribute(String flag) {
        if (get() == null) {
            return ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest().getSession().getAttribute(flag);
        } else {
            return getSession().getAttribute(flag);
        }
    }

    /**
     * 删除缓存到session信息
     *
     * @param flag 缓存key
     */
    public static void removeSessionAttribute(String flag) {
        if (get() == null) {
            ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest().getSession().removeAttribute(flag);
        } else {
            getSession().removeAttribute(flag);
        }
    }

    /**
     * 为用户签发token
     */
    public static void setToken(String token){
    	if(StringUtil.isEmpty(token)){
    		throw new CommonException(Error.biz_error);
    	}
    	getSession().setAttribute(Context.session_token, token);
    }
    
    /**
     * 获取用户授权的token值，用于解密请求数据
     * @return
     */
    public static String getToken(){
//    	//获取用户请求的授权key
//    	String authorization = get().getHeader("Authorization");
//    	if(StringUtil.isEmpty(authorization)){
//    		return null;
//    	}
//    	Object token = getSessionAttribute(authorization);
//    	if(StringUtil.isEmpty(token)){
//    		return null;
//    	}
//    	return token.toString();
//    	Object token = getSession().getAttribute(Context.session_token);
//    	if(StringUtil.isEmpty(token)){
//    		return null;
//    	}
//    	return token.toString();
    	return "1234567890123456";
    }
    
    /**
     * 将用户请求的数据同步到request
     * @param json
     */
    @SuppressWarnings("unchecked")
	public static Map<String, Object> synchronizeParam(String json){
    	//最终要放回request的参数
    	Map<String, Object> param = new HashMap<String, Object>();
    	//用户请求的json参数
    	Map<String, Object> map = JsonUtil.jsonToMap(json);
    	Set<Entry<String, Object>> set = map.entrySet();
    	for (Entry<String, Object> entry : set) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if(value instanceof Map){
				Map<String, Object> mapValue = (Map<String, Object>) value;
				putMapParam(mapValue,key,param);
				continue;
			}
			param.put(key, value.toString());
		}
    	return param;
    }
    
    /**
     * 添加map参数到request
     * @param mapValue
     * @param key
     * @param param
     */
    @SuppressWarnings("unchecked")
	private static void putMapParam(Map<String, Object> mapValue, String key, Map<String, Object> param){
    	Set<Entry<String, Object>> set = mapValue.entrySet();
    	for (Entry<String, Object> entry : set){
    		String key2 = entry.getKey();
    		Object value = entry.getValue();
    		if(value instanceof Map){
    			Map<String, Object> map = (Map<String, Object>) value;
				putMapParam(map, key+"."+key2, param);
			}else{
				param.put(key+"."+key2, value);
			}
    	}
    }
    
    /**
     * 当请求为form表单的时候，加密采取key=加密val
     * 此方法用于获取key的名称
     * @return
     */
    public static String getAESParamKeyName(){
    	return "body";
    }
    
    @PostConstruct
    private void init(){
    	if(enableAuth != null){
    		auth = enableAuth;
    	}
    }
}
